<template>
  <section>
    <van-sticky>
      <PageHeader title="创建活动"/>
    </van-sticky>

    <van-form @submit="onFormSubmit">
      <van-field
        v-model="activity.name"
        name="name"
        label="名称"
        placeholder="请输入活动名称"
        required
        :rules="[{ required: true, message: '活动名称不能为空' }]"
      />

      <van-field
        v-model="activity.vip_card_name"
        readonly
        label="会员卡"
        placeholder="请选择会员卡"
        is-link
        @click="vipCardActionVisible=true">
      </van-field>

      <van-cell-group title="活动时间">
        <van-field
          v-model="activity.begin_time_str"
          disabled
          required
          label="开始时间"
          placeholder="请选择开始时间"
          :rules="[{ required: true, message: '请选择开始时间' }]"
          is-link
          @click="showActivityTimePopup('begin')">
        </van-field>

        <van-field
          v-model="activity.end_time_str"
          disabled
          required
          label="结束时间"
          placeholder="请选择结束时间"
          :rules="[{ required: true, message: '请选择结束时间' }]"
          is-link
          @click="showActivityTimePopup('end')">
        </van-field>
      </van-cell-group>

      <van-cell-group title="参与要求">
        <van-field
          v-model="activity.apply_requirement_desc"
          label="要求描述"
          placeholder="请输入参与要求"
          type="textarea"
          autosize
          rows="5">
        </van-field>

        <van-cell center title="需实名认证">
          <template #right-icon>
            <van-switch v-model="activity.realname_auth_required" :active-value="1" :inactive-value="0" size="24" />
          </template>
        </van-cell>

        <van-cell center title="需关注公众号">
          <template #right-icon>
            <van-switch v-model="activity.subscribe_mp_required" :active-value="1" :inactive-value="0" size="24" />
          </template>
        </van-cell>

        <van-field
          v-model="activity.times"
          name="times"
          label="每人可参与"
          placeholder="请输入每人可参与的次数"
          type="digit"
          required
          :rules="[{ required: true, message: '次数不能为空' }]">
          <template #button>
            <label>次</label>
          </template>
        </van-field>

        <van-field
          v-model="activity.max_joiner"
          name="max_joiner"
          label="最多参与人次"
          placeholder="请输入最多可参与人次"
          type="digit"
          required
          :rules="[{ required: true, message: '人次不能为空' }]">
          <template #button>
            <label>次</label>
          </template>
        </van-field>

      </van-cell-group>

      <van-cell-group title="详情">
        <Ueditor :defaultMsg="activity.detail" :config="ueConfig" id="ue" ref="ue"/>
      </van-cell-group>

      <van-cell center title="上线">
        <template #right-icon>
          <van-switch v-model="activity.enable" :active-value="1" :inactive-value="0" size="24" />
        </template>
      </van-cell>

      <van-field
        v-model="activity.join_btn_label"
        name="job_btn_label"
        label="参与按钮文本"
        placeholder="请输入参与按钮文本"
        required
        :rules="[{ required: true, message: '文本不能为空' }]">
      </van-field>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>

    <van-popup v-model="datetimePickerPopupVisible" round position="bottom">
      <van-datetime-picker
        v-model="activityTime"
        type="datetime"
        title="活动时间"
        @confirm="onActivityTimeConfirm"/>
    </van-popup>

    <van-action-sheet
      v-model="vipCardActionVisible"
      :actions="vipCardActions"
      @select="onVipCardSelect"
      cancel-text="取消"
      close-on-click-action />
  </section>
</template>

<script>
import PageHeader from "../../componets/PageHeader";
import Ueditor from "../../../components/Ueditor";
import {
  BASE_PATH,
  ueFileUploadUri,
  vipCardAllUri,
  marketingActivitySaveUri,
  marketingActivityInfoUri
} from "../../../common/api";
import util from '../../../assets/js/util';

export default {
  components: {
    PageHeader,
    Ueditor
  },
  data() {
    const ueServerUrl = ueFileUploadUri + '?upload_token=' + this.GLOBAL.userInfo.upload_token;
    return {
      ueConfig: {
        UEDITOR_HOME_URL: BASE_PATH + '/static/js/ueditor/',
        serverUrl: ueServerUrl,
        initialFrameWidth: null,
        initialFrameHeight: 400
      },
      activity: {
        id: 0, name: '', detail: '', begin_time: 0, end_time: 0, begin_time_str: '', end_time_str: '', apply_requirement_desc: '',
        vip_card_id: '', vip_card_name: '', realname_auth_required: 1, subscribe_mp_required: 1, times: 1, max_joiner: 10, join_btn_label: '立即参与', enable: 1
      },
      datetimePickerPopupVisible: false,
      activityTime: new Date(),
      activityTimeType: '',

      vipCardActionVisible: false,
      vipCardActions: []
    }
  },
  methods: {
    showActivityTimePopup(type) {
      this.activityTimeType = type;
      this.datetimePickerPopupVisible = true;
    },
    onActivityTimeConfirm(value) {
      if (this.activityTimeType == 'begin') {
        this.activity.begin_time = value.getTime() / 1000;
        this.activity.begin_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + value.getHours() + ':' + value.getMinutes();
      } else if (this.activityTimeType == 'end') {
        this.activity.end_time = value.getTime() / 1000;
        this.activity.end_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + value.getHours() + ':' + value.getMinutes();
      }
      this.datetimePickerPopupVisible = false;
    },
    getVipCards() {
      const that = this;
      this.$http.get(vipCardAllUri).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          let vipCardActions = [];
          for (let k = 0; k < data.cards.length; k++) {
            vipCardActions.push({
              name: data.cards[k].name,
              id:data.cards[k].id,
              index: k
            });
          }
          that.vipCardActions = vipCardActions;
        }
      }, response => {
        // error callback
      })
    },
    onVipCardSelect(item) {
      this.activity.vip_card_id = item.id;
      this.activity.vip_card_name = item.name;
    },
    onFormSubmit(values) {
      this.activity.detail = this.$refs.ue.getUEContent();
      const that = this;
      that.$http.post(marketingActivitySaveUri, that.activity, {emulateJSON: true}).then(response => {
        let {msg, code, data} = response.body;
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          that.toast.success('保存成功');
          that.$router.back();
        }
      }, response => {
        that.toast.fail('发生错误');
      })
    },
    getInfo() {
      const id = this.$route.params.id;
      const that = this;
      this.$http.get(marketingActivityInfoUri + '?id=' + id).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          that.activity = data.activity;
          that.activity.begin_time_str = util.dateFormat(that.activity.begin_time, 'yyyy-MM-dd hh:mm:ss');
          that.activity.end_time_str = util.dateFormat(that.activity.end_time, 'yyyy-MM-dd hh:mm:ss');
          that.$refs.ue.setUEContent(data.activity.detail);
        }
      }, response => {
        // error callback
      })
    }
  },
  mounted: function () {
    this.getVipCards();
    if(this.$route.name == 'MarketingEditActivity') {
      this.getInfo();
    }
  }
}
</script>

<style scoped>

</style>
